const Koa = require('koa');
const router = require('koa-router')()
const fs = require('fs');
//const JSON5 = require('json5')
const bodyParser = require('koa-bodyparser');
const viewRender = require('./lib/ejs-render')
const path = require('path')
const static = require('koa-static')


const app = new Koa();
// A body parser for koa
app.use(bodyParser());
// vue-rander
app.use(viewRender(path.join(__dirname + '/controllers')))
// console.info(path.join(__dirname + '/static'))
app.use(static(path.join(__dirname + '/static'))) 



// x-response-time
app.use(async (ctx, next) => {
  console.log(new Date().toLocaleString() + ` @ Process  ${ctx.request.method} ${ctx.request.url}...`)
  try {
    await next(); 
  } catch (err) { 
    ctx.response.type = 'text/html';
    ctx.response.body = '<p>Something wrong, please contact administrator.</p>'
      + (process.env.NODE_ENV == 'dev' ? '<pre>' +  err + '</pre>' : '')
    //ctx.cookies.set('koa_page_error', err);
    ctx.app.emit('error', err, ctx);
	  //throw new Error(err)
  }
  //ctx.set('X-Response-Time', `${ms}ms`); 
});

app.on('error', (err, ctx) => { 
  err.NODE_ENV = process.env.NODE_ENV
  if (process.env.NODE_ENV == 'dev') {
    //throw new Error(err)
    console.error(err);
  } else {
    console.error(err);
  }
});

 
let files = fs.readdirSync(__dirname + '/router').filter(f => f.endsWith('.js'))
files.forEach(item => {
	let file = require(__dirname + '/router/' + item)
	let baseurl = file.basepath == '/' ? '' : '/' + item.replace(/.js/g, '')
	file.routeArr.forEach(route => {
		router[route.method.toLowerCase()](baseurl + route.path, route.func)
	})
})

router.get('*', async (ctx, next) => {
  // 重定向，去首页
  //ctx.response.redirect('/other')
  ctx.body = `<h1>404了</h1>`
})


// add router middleware:
app.use(router.routes());
app.listen(3000);
console.log('app started at port 3000...');

